<script setup lang="ts">
import type { User } from '@/types/mall'
import { formatPrice } from '@/utils/mall'

const router = useRouter()
const userStore = useUserStore()
const orderStore = useOrderStore()

// 用户信息
const userInfo = computed(() => (userStore as any).user)
const isLoggedIn = computed(() => {
  // 临时设置为true以便测试页面跳转
  return true
  // const loggedIn = (userStore as any).isLoggedIn
  // console.log('User login status:', loggedIn)
  // return loggedIn
})
const userAvatar = computed(() => (userStore as any).userAvatar || 'https://via.placeholder.com/100x100?text=头像')
const userNickname = computed(() => (userStore as any).userNickname || '测试用户')
const userPoints = computed(() => (userStore as any).userPoints || 100)
const userBalance = computed(() => (userStore as any).userBalance || 0)

// 订单统计
const orderStats = computed(() => (orderStore as any).orderStatistics)

// 菜单列表
const menuItems = [
  {
    icon: 'location',
    title: '收货地址',
    path: '/subPackages/user-package/address/list',
    arrow: true
  },
  {
    icon: 'star-on',
    title: '我的收藏',
    path: '/subPackages/user-package/favorite/list',
    arrow: true
  },
  {
    icon: 'coupon',
    title: '优惠券',
    path: '/subPackages/user-package/coupon/list',
    arrow: true,
    badge: '3'
  },
  {
    icon: 'goods',
    title: '趣味小游戏',
    path: '/subPackages/game-package/list/index',
    arrow: true,
    badge: 'NEW'
  },
  {
    icon: 'feedback',
    title: '意见反馈',
    path: '/subPackages/common-package/feedback/index',
    arrow: true
  },
  {
    icon: 'setting',
    title: '设置',
    path: '/subPackages/user-package/setting/index',
    arrow: true
  }
]

// 跳转到登录页面
function goToLogin() {
  // TODO: 登录页面待开发
  uni.showToast({ title: '登录功能待开发', icon: 'none' })
}

// 跳转到个人信息页面
function goToProfile() {
  if (!isLoggedIn.value) {
    goToLogin()
    return
  }
  // TODO: 个人信息页面待开发
  uni.showToast({ title: '个人信息页面待开发', icon: 'none' })
}

// 跳转到订单列表
function goToOrderList(status?: string) {
  if (!isLoggedIn.value) {
    goToLogin()
    return
  }
  
  const url = status 
    ? `/subPackages/user-package/order/list?status=${status}`
    : '/sub-packages/user-package/order/list'
  uni.navigateTo({ url })
}

// 跳转到菜单页面
function goToMenuPage(path: string) {
  console.log('Clicking menu item:', path)
  console.log('Is logged in:', isLoggedIn.value)
  
  // 需要登录的页面
  const needLoginPages = [
    '/subPackages/user-package/address/list', 
    '/subPackages/user-package/favorite/list', 
    '/subPackages/user-package/coupon/list',
    '/subPackages/user-package/setting/index'
  ]
  
  if (needLoginPages.includes(path)) {
    if (!isLoggedIn.value) {
      console.log('Need login, redirecting to login page')
      goToLogin()
      return
    }
  }
  
  console.log('Navigating to:', path)
  uni.navigateTo({ 
    url: path,
    success: () => {
      console.log('Navigation success to:', path)
    },
    fail: (err) => {
      console.error('Navigation failed:', err, path)
      uni.showToast({ title: '页面跳转失败', icon: 'none' })
    }
  })
}

// 用户登出
async function logout() {
  uni.showModal({
    title: '确认退出',
    content: '确定要退出登录吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          await (userStore as any).logout()
          uni.showToast({ title: '已退出登录', icon: 'success' })
        } catch (error) {
          console.error('退出登录失败:', error)
        }
      }
    }
  })
}

// 页面生命周期
onMounted(async () => {
  try {
    await (userStore as any).initUser()
    if (isLoggedIn.value) {
      await (orderStore as any).getOrderList()
    }
  } catch (error) {
    console.error('初始化用户信息失败:', error)
  }
})
</script>

<template>
  <view class="min-h-screen bg-gray-50">
    <!-- 用户信息区域 -->
    <view class="bg-gradient-to-br from-indigo-500 to-purple-600 p-5 flex items-center justify-between mb-2.5">
      <view class="flex items-center flex-1" @click="goToProfile">
        <image :src="userAvatar" class="w-15 h-15 rounded-full mr-4 border-2 border-white border-opacity-30" mode="aspectFill" />
        
        <view class="flex-1">
          <view v-if="isLoggedIn" class="flex items-center gap-2 mb-2">
            <text class="text-lg font-bold text-white">{{ userNickname }}</text>
            <wd-icon name="arrow-right" size="16px" color="#999" />
          </view>
          <view v-else class="flex items-center gap-2">
            <text class="text-base text-white">点击登录</text>
            <wd-icon name="arrow-right" size="16px" color="#999" />
          </view>
          
          <view v-if="isLoggedIn" class="flex gap-4">
            <text class="text-xs text-white text-opacity-80">积分：{{ userPoints }}</text>
            <text class="text-xs text-white text-opacity-80">余额：{{ formatPrice(userBalance) }}</text>
          </view>
        </view>
      </view>
      
      <!-- 退出登录按钮 -->
      <view v-if="isLoggedIn" class="p-2 bg-white bg-opacity-20 rounded-full" @click="logout">
        <wd-icon name="logout" size="20px" color="#666" />
      </view>
    </view>

    <!-- 订单统计 -->
    <view v-if="isLoggedIn" class="bg-white mb-2.5 p-4">
      <view class="flex items-center justify-between mb-4">
        <text class="text-base font-bold text-gray-800">我的订单</text>
        <view class="flex items-center gap-1 text-xs text-gray-400" @click="goToOrderList()">
          <text>查看全部</text>
          <wd-icon name="arrow-right" size="12px" color="#999" />
        </view>
      </view>
      
      <view class="flex justify-around">
        <view class="flex flex-col items-center gap-2" @click="goToOrderList('pending_payment')">
          <view class="relative">
            <wd-icon name="pay" size="24px" color="#ff4142" />
            <view v-if="orderStats.pendingPayment > 0" class="absolute -top-1 -right-1 bg-red-500 text-white text-xs min-w-4 h-4 rounded-2 flex items-center justify-center leading-none">
              {{ orderStats.pendingPayment }}
            </view>
          </view>
          <text class="text-xs text-gray-600">待付款</text>
        </view>
        
        <view class="flex flex-col items-center gap-2" @click="goToOrderList('pending_shipment')">
          <view class="relative">
            <wd-icon name="goods" size="24px" color="#ff8800" />
            <view v-if="orderStats.pendingShipment > 0" class="absolute -top-1 -right-1 bg-red-500 text-white text-xs min-w-4 h-4 rounded-2 flex items-center justify-center leading-none">
              {{ orderStats.pendingShipment }}
            </view>
          </view>
          <text class="text-xs text-gray-600">待发货</text>
        </view>
        
        <view class="flex flex-col items-center gap-2" @click="goToOrderList('shipped')">
          <view class="relative">
            <wd-icon name="logistics" size="24px" color="#4dabf7" />
            <view v-if="orderStats.shipped > 0" class="absolute -top-1 -right-1 bg-red-500 text-white text-xs min-w-4 h-4 rounded-2 flex items-center justify-center leading-none">
              {{ orderStats.shipped }}
            </view>
          </view>
          <text class="text-xs text-gray-600">待收货</text>
        </view>
        
        <view class="flex flex-col items-center gap-2" @click="goToOrderList('delivered')">
          <view class="relative">
            <wd-icon name="comment" size="24px" color="#00d100" />
            <view v-if="orderStats.delivered > 0" class="absolute -top-1 -right-1 bg-red-500 text-white text-xs min-w-4 h-4 rounded-2 flex items-center justify-center leading-none">
              {{ orderStats.delivered }}
            </view>
          </view>
          <text class="text-xs text-gray-600">待评价</text>
        </view>
      </view>
    </view>

    <!-- 功能菜单 -->
    <view class="bg-white mb-2.5">
      <view>
        <view
          v-for="item in menuItems"
          :key="item.title"
          class="flex items-center p-4 border-b border-gray-100 last:border-b-0"
          @click="goToMenuPage(item.path)"
        >
          <view class="w-10 h-10 bg-gray-50 rounded-full flex items-center justify-center mr-3">
            <wd-icon :name="item.icon" size="20px" color="#666" />
          </view>
          
          <text class="flex-1 text-sm text-gray-800">{{ item.title }}</text>
          
          <view class="flex items-center gap-2">
            <view v-if="item.badge" class="bg-red-500 text-white text-xs px-1.5 py-0.5 rounded-2 min-w-4 text-center">
              {{ item.badge }}
            </view>
            <wd-icon v-if="item.arrow" name="arrow-right" size="16px" color="#999" />
          </view>
        </view>
      </view>
    </view>

    <!-- 版本信息 -->
    <view class="text-center py-5">
      <text class="text-xs text-gray-400">版本 1.0.0</text>
    </view>
  </view>
</template>

<route lang="json">
{
  "name": "user",
  "layout": "tabbar",
  "style": {
    "navigationBarTitleText": "我的"
  }
}
</route>